import {
	Message,
	Modal
} from 'view-design';
import {
	setStore
} from '@/libs/storage';
import {
	removeCookie
} from '@/libs/cookies';
export default function({
	store,
	req,
	redirect,
	route,
	app: {
		$axios
	}
}) {
	// 数据访问前缀
	// if(process.server){
	//     // 获取服务端的token
	// }
	// if(process.client){
	//     // 获取客户端token
	// }
	let path;
	if (process.server) {
		path = req.originalUrl;
		//console.log('server',req.originalUrl)
	}
	if (process.client) {
		path = route.path;
		//  console.log('client',route.path)
	}
	// // request拦截器
	$axios.onRequest(config => {
		if (config.url == '/common/site') {
			config.data = {
				path: path
			}
		}
		return config;
	});

	$axios.onResponse(res => {
		const data = res.data;
		// console.log(data)
		// 根据返回的code值来做不同的处理(和后端约定)
		switch (data.code) {
			case 401:
				if (process.client) {
					Message.error(data.message ? data.message : '登录超时，请重新登录')
				}
				// 未登录 清除已登录状态
				removeCookie('USER_INFO');
				setStore('ACCESS_TOKEN', '');
				redirect('/login');
				break;
			case 403:
				// 没有权限
				if (process.client) {
					Message.error(data.message ? data.message : '权限异常')
				}
				break;
			case 500:
				// 错误
				if (process.client) {
					Message.error(data.message ? data.message : '服务器异常')
				}
				break;
			case 700:
				// 错误
				if (process.client) {
					Modal.error({
					  title: "温馨提示",
					  content: '权限异常，当前页面用户与实际登录用户不符，请重新登录',
					  loading: true,
					  onOk: () => {
						  Modal.remove();
						 // 未登录 清除已登录状态
						 removeCookie('USER_INFO');
						 setStore('ACCESS_TOKEN', '');
						 redirect('/login');
					  },
					});
				}
				break;
			default:
				return data;
		}

		return data;
	});
	$axios.onError(err => {
		if (process.client) {
			Message.error('请求异常')
		}
		return Promise.reject(err)
	});
}
